<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use Exception;

/**
 * MRP物料需求计划
 *
 * @icon fa fa-calculator
 * @remark MRP运算、采购建议、生产建议
 */
class Mrp extends Backend
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\MrpPlan;
    }

    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            return json(["total" => $list->total(), "rows" => $list->items()]);
        }
        return $this->view->fetch();
    }

    /**
     * 执行MRP运算
     */
    public function run($ids = null)
    {
        $plan = $this->model->get($ids);
        if (!$plan) {
            $this->error(__('No Results were found'));
        }

        Db::startTrans();
        try {
            // 更新状态为运算中
            $plan->run_status = 1;
            $plan->run_time = time();
            $plan->save();

            // 执行MRP运算逻辑
            $this->executeMrpCalculation($plan);

            // 更新状态为已完成
            $plan->run_status = 2;
            $plan->save();

            Db::commit();
            $this->success('MRP运算完成');
        } catch (Exception $e) {
            Db::rollback();
            $plan->run_status = 3;
            $plan->error_msg = $e->getMessage();
            $plan->save();
            $this->error($e->getMessage());
        }
    }

    /**
     * MRP运算核心逻辑
     */
    private function executeMrpCalculation($plan)
    {
        // 1. 获取所有生产订单和生产计划
        $orders = Db::name('scanwork_order')
            ->where('status', '<>', 2)
            ->where('delivery_date', 'between', [$plan->start_date, $plan->end_date])
            ->select();

        // 2. 根据BOM展开物料需求
        foreach ($orders as $order) {
            $this->expandBomRequirement($plan->id, $order);
        }

        // 3. 计算净需求
        $this->calculateNetRequirement($plan->id);

        // 4. 生成采购建议和生产建议
        $this->generateSuggestions($plan->id);
    }

    /**
     * BOM展开
     */
    private function expandBomRequirement($planId, $order)
    {
        // 简化版BOM展开逻辑
        // 实际应该递归展开多层BOM
        
        $bom = Db::name('scanwork_bom')
            ->where('product_id', $order['product_id'])
            ->where('status', 2)
            ->find();

        if ($bom) {
            $bomItems = Db::name('scanwork_bom_item')
                ->where('bom_id', $bom['id'])
                ->select();

            foreach ($bomItems as $item) {
                Db::name('scanwork_mrp_requirement')->insert([
                    'plan_id' => $planId,
                    'material_id' => $item['material_id'],
                    'requirement_type' => 2,
                    'source_type' => 'order',
                    'source_id' => $order['id'],
                    'source_no' => $order['order_no'],
                    'requirement_date' => $order['delivery_date'],
                    'gross_requirement' => $item['quantity'] * $order['quantity'],
                    'createtime' => time()
                ]);
            }
        }
    }

    /**
     * 计算净需求
     */
    private function calculateNetRequirement($planId)
    {
        $requirements = Db::name('scanwork_mrp_requirement')
            ->where('plan_id', $planId)
            ->select();

        foreach ($requirements as $req) {
            // 获取当前库存
            $stock = Db::name('scanwork_stock')
                ->where('material_id', $req['material_id'])
                ->sum('quantity');

            // 计算净需求
            $netReq = $req['gross_requirement'] - $stock;
            
            if ($netReq > 0) {
                Db::name('scanwork_mrp_requirement')
                    ->where('id', $req['id'])
                    ->update([
                        'on_hand_stock' => $stock,
                        'net_requirement' => $netReq,
                        'planned_order' => $netReq
                    ]);
            }
        }
    }

    /**
     * 生成建议
     */
    private function generateSuggestions($planId)
    {
        $requirements = Db::name('scanwork_mrp_requirement')
            ->where('plan_id', $planId)
            ->where('net_requirement', '>', 0)
            ->select();

        foreach ($requirements as $req) {
            // 判断是采购件还是自制件
            $material = Db::name('scanwork_material')
                ->where('id', $req['material_id'])
                ->find();

            if ($material) {
                if ($material['type'] == 'raw' || $material['type'] == 'auxiliary') {
                    // 生成采购建议
                    $this->createPurchaseSuggest($planId, $req, $material);
                } else {
                    // 生成生产建议
                    $this->createProductionSuggest($planId, $req, $material);
                }
            }
        }
    }

    /**
     * 创建采购建议
     */
    private function createPurchaseSuggest($planId, $req, $material)
    {
        Db::name('scanwork_mrp_purchase_suggest')->insert([
            'plan_id' => $planId,
            'suggest_no' => 'PS-' . date('YmdHis') . rand(1000, 9999),
            'material_id' => $req['material_id'],
            'material_code' => $material['material_code'],
            'material_name' => $material['material_name'],
            'suggest_quantity' => $req['net_requirement'],
            'unit' => $material['unit'],
            'suggest_date' => date('Y-m-d'),
            'required_date' => $req['requirement_date'],
            'supplier_id' => $material['supplier_id'],
            'estimated_price' => $material['price'],
            'estimated_amount' => $req['net_requirement'] * $material['price'],
            'status' => 0,
            'createtime' => time()
        ]);
    }

    /**
     * 创建生产建议
     */
    private function createProductionSuggest($planId, $req, $material)
    {
        Db::name('scanwork_mrp_production_suggest')->insert([
            'plan_id' => $planId,
            'suggest_no' => 'PDS-' . date('YmdHis') . rand(1000, 9999),
            'material_id' => $req['material_id'],
            'material_code' => $material['material_code'],
            'material_name' => $material['material_name'],
            'suggest_quantity' => $req['net_requirement'],
            'unit' => $material['unit'],
            'suggest_start_date' => date('Y-m-d'),
            'suggest_end_date' => date('Y-m-d', strtotime($req['requirement_date'] . ' -3 days')),
            'required_date' => $req['requirement_date'],
            'status' => 0,
            'createtime' => time()
        ]);
    }

    /**
     * 采购建议列表
     */
    public function purchaseSuggest()
    {
        if ($this->request->isAjax()) {
            $planId = $this->request->get('plan_id');
            
            $list = Db::name('scanwork_mrp_purchase_suggest')
                ->where('plan_id', $planId)
                ->order('id', 'desc')
                ->select();

            return json(['code' => 1, 'data' => $list]);
        }
        return $this->view->fetch();
    }

    /**
     * 生产建议列表
     */
    public function productionSuggest()
    {
        if ($this->request->isAjax()) {
            $planId = $this->request->get('plan_id');
            
            $list = Db::name('scanwork_mrp_production_suggest')
                ->where('plan_id', $planId)
                ->order('id', 'desc')
                ->select();

            return json(['code' => 1, 'data' => $list]);
        }
        return $this->view->fetch();
    }

    /**
     * 物料需求详情
     */
    public function requirement()
    {
        if ($this->request->isAjax()) {
            $planId = $this->request->get('plan_id');
            
            $list = Db::name('scanwork_mrp_requirement')
                ->alias('r')
                ->join('scanwork_material m', 'r.material_id = m.id')
                ->where('r.plan_id', $planId)
                ->field('r.*, m.material_code, m.material_name, m.spec, m.unit')
                ->order('r.requirement_date', 'asc')
                ->select();

            return json(['code' => 1, 'data' => $list]);
        }
        return $this->view->fetch();
    }
}

